
import { defineStore } from 'pinia';

export interface Todo {
	id : number;
	text : string;
	completed : boolean;
}

export const useUserStore = defineStore('USER', {
	state: () => ({
		islogin: false,
		member: {},
		systemInfo: {}, // --设备信息
		__key_member: 'usedt_member',
		__key_token: 'uni_id_token',
		__key_token_expired: 'uni_id_token_expired',
		todos: [] as Todo[]
	}),
	actions: {
		// 登录成功
		login(res:any) {
			// 用户已登录
			this.islogin = true;
		
			this.member = res.member;
			this.token = res.user.token;
			this.token_expired = res.user.tokenExpired;
		
			// 存储会员 member 数据
			uni.setStorage({
				key: this.__key_member,
				data: this.member
			})
		
			// 存储uid token 数据
			uni.setStorage({
				key: this.__key_token,
				data: this.token
			})
			// 存储uid token_expired 数据
			uni.setStorage({
				key: this.__key_token_expired,
				data: this.token_expired
			})
		},
		
		// 注销 
		logout(state:any) {
			this.islogin = false;
			this.member = {};
			this.token = '';
			this.token_expired = 0;
			this.memberState = false;
			this.memberList = [];
			uni.removeStorage({
				key: this.__key_member
			})
			
			uni.removeStorage({
				key: 'use_member_list'
			})
			uni.removeStorage({
				key: this.__key_token
			})
			uni.removeStorage({
				key: this.__key_token_expired
			})
		},
		
		// 加载 Token
		loadToken(state) {
			state.member = uni.getStorageSync(state.__key_member);
			state.token = uni.getStorageSync(state.__key_token);
			state.token_expired = uni.getStorageSync(state.__key_token_expired);
		
			if (state.token_expired > new Date().getTime()) {
				state.islogin = true;
			}
		},
		// token 令牌
		token(state, token, token_expired) {
			state.token = token;
			state.token_expired = token_expired;
		
			// 存储uid token 数据
			uni.setStorage({
				key: state.__key_token,
				data: state.token
			})
			// 存储uid token_expired 数据
			uni.setStorage({
				key: state.__key_token_expired,
				data: state.token_expired
			})
		},
		addTodo(text : string) {
			const newTodo : Todo = {
				id: Date.now(),
				text,
				completed: false
			};
			this.todos.push(newTodo);
		},
		removeTodo(id : number) {
			this.todos = this.todos.filter(todo => todo.id !== id);
		},
		toggleTodo(id : number) {
			this.todos = this.todos.map(todo => (todo.id === id ? { ...todo, completed: !todo.completed } : todo));
		}
	},
	getters: {
		todosCount: (state : { todos : Todo[] }) => state.todos.length,
		completedTodos: (state : { todos : Todo[] }) => state.todos.filter(todo => todo.completed)
	}
});